﻿using Loogn.OrmLite;
using MicroConfig.NetCore.Server.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MicroConfig.NetCore.Server.Services
{
    public class ConfigItemService
    {
        public static readonly ConfigItemService Instance = new ConfigItemService();

        private List<ConfigItem> s_cacheList = null;
        private bool reload = false;
        private object obj = new object();

        public List<ConfigItem> CacheList
        {
            get
            {
                lock (obj)
                {
                    if (reload || s_cacheList == null)
                    {
                        s_cacheList = SelectAll();
                        reload = false;
                    }
                    return s_cacheList;
                }
            }
        }

        private List<ConfigItem> SelectAll()
        {
            using (var db = DB.Open())
            {
                return db.Select<ConfigItem>();
            }
        }


        public OrmLitePageResult<ConfigItem> SelectPage(long? projectId, string kw, int pageIndex, int pageSize)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("1=1");
            if (projectId > 0)
            {
                sb.AppendFormat(" and ProjectId={0}", projectId);
            }
            kw = SqlInjection.Filter(kw);
            if (!string.IsNullOrEmpty(kw))
            {
                sb.AppendFormat(" and key like '%{0}%'", kw);
            }
            using (var db = DB.Open())
            {
                return db.SelectPage<ConfigItem>(new OrmLitePageFactor
                {
                    TableName = "ConfigItem c inner join Project p on c.ProjectId=p.Id",
                    Fields = "c.*,p.Name as ProjectName",
                    Conditions = sb.ToString(),
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    OrderBy = "c.id asc",
                });
            }
        }

        public ResultObject Delete(long id)
        {
            using (var db = DB.Open())
            {
                db.DeleteById<ConfigItem>(id);
            }
            reload = true;
            return new ResultObject
            {
                Msg = "删除成功",
                Success = true,
            };
        }

        public ResultObject Add(ConfigItem m)
        {
            if (m.ProjectId == 0)
            {
                return new ResultObject { Msg = "项目不能为空" };
            }
            if (string.IsNullOrEmpty(m.Key))
            {
                return new ResultObject { Msg = "key不能为空" };
            }
            using (var db = DB.Open())
            {
                var count = db.CountWhere<ConfigItem>(DictBuilder
                    .Assign("Environment", m.Environment ?? "")
                    .Assign("Key", m.Key));
                if (count > 0)
                {
                    return new ResultObject { Msg = "该环境下的key已存在" };
                }

                db.Insert(m);
                reload = true;
                return new ResultObject
                {
                    Success = true,
                    Msg = "添加成功"
                };
            }
        }

        public ResultObject Update(long id, string value)
        {
            using (var db = DB.Open())
            {
                db.UpdateFieldById<ConfigItem>("Value", value, id);
            }
            reload = true;
            return new ResultObject
            {
                Success = true,
                Msg = "修改成功"
            };
        }
    }
}
